package com.tc.interceptor;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// JWT认证
@Component
public class CheckTokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


         //跳过登录、验证码等公开接口
        String requestURI = request.getRequestURI();
        if (isPublicPath(requestURI)) {
            return true;
        }
        // 获取token
        String token = request.getHeader("token");
        // 校验token
        if (token == null) {
            throw new Exception("token为空，请登录！！！");
        } else {
            // 校验token的有效性（正确性、时效性）
            JwtParser parser = Jwts.parser();
            // 解析token的SigningKey必须和生成token时设置的密码一致
            parser.setSigningKey("ybbx");// 这里的"ybbx"是生成token时使用的密钥，必须与之保持一致
            // 如果token正确则正常执行，否则抛出异常
            Jws<Claims> claimsJws = parser.parseClaimsJws(token);
        }
        return true;
    }

    private boolean isPublicPath(String path) {
        return path.contains("/doc.html") ||
                path.contains("/swagger-ui") ||
                path.contains("/webjars/") ||
                path.contains("/swagger-resources") ||
                path.contains("/v2/api-docs") ||
                path.contains("/v3/api-docs") ||
                path.startsWith("/auth/");
    }
}